package com.freesun.monitor.fs;

import java.io.*;

//import com.freesun.web.common.utils.FileUtil;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;

/**
 * 测试上传
 *
 * @author yangfei
 * @created  2013-12-11
 * @desc  对fastdfs服务器集群进行性能测试验证，首次测试为添加缓存服务，二次验证增加缓存服务
 * @update 增加连接socket ProtoCommon.activeTest(trackerServer.getSocket());保存连接通常
 */
public class FastDfs {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * @des 文件上传
     * @param clientPath
     * @param localFilePath
     * @throws IOException
     * @throws MyException
     */
    public int uploadFile(String clientPath,String localFilePath) throws IOException, MyException {

        log.debug("配置文件:" + clientPath);
        //lr.message("配置文件:" + clientPath);
        ClientGlobal.init(clientPath);

        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        trackerServer.getSocket().setKeepAlive(true);
        //网络正常后发送数据保存连接
        ProtoCommon.activeTest(trackerServer.getSocket());


        StorageServer storageServer = null;
        StorageClient storageClient = new StorageClient(trackerServer, storageServer);

        NameValuePair[] meta_list = new NameValuePair[3];
        meta_list[0] = new NameValuePair("width", "500");
        meta_list[1] = new NameValuePair("heigth", "750");
        meta_list[2] = new NameValuePair("author", "yangfei");

        File file = new File(localFilePath);
        FileInputStream fis = new FileInputStream(file);
        byte[] file_buff = null;

        try{
            if (fis != null) {
                int len = fis.available();
                file_buff = new byte[len];
                fis.read(file_buff);
            }
        }finally
        {
            fis.close();
        }




        log.debug("file length: " + file_buff.length);
        ////lr.message("file length: " + file_buff.length);

        //定义组名
        String group_name = null;
        StorageServer[] storageServers = trackerClient.getStoreStorages(trackerServer, group_name);

        if (storageServers == null) {
            log.debug("get store storage servers fail, error code: " + storageClient.getErrorCode());
            //lr.message("get store storage servers fail, error code: " + storageClient.getErrorCode());
        } else {
            log.debug("store storage servers count: " + storageServers.length);
            //lr.message("store storage servers count: " + storageServers.length);
            for (int k = 0; k < storageServers.length; k++) {
                log.debug(k + 1 + ". " + storageServers[k].getInetSocketAddress().getAddress().getHostAddress() + ":" + storageServers[k].getInetSocketAddress().getPort());
                //lr.message(k + 1 + ". " + storageServers[k].getInetSocketAddress().getAddress().getHostAddress() + ":" + storageServers[k].getInetSocketAddress().getPort());
            }
            log.debug("");
            //lr.message("");
        }

        long startTime = System.currentTimeMillis();
        String[] results = storageClient.upload_file(file_buff, "jpg", meta_list);
        log.debug("upload_file time used: " + (System.currentTimeMillis() - startTime) + " ms");
        //lr.message("upload_file time used: " + (System.currentTimeMillis() - startTime) + " ms");

        if (results == null) {
            log.debug("upload file fail, error code: " + storageClient.getErrorCode());
            //lr.message("upload file fail, error code: " + storageClient.getErrorCode());
            return 0;
        }

        group_name = results[0];
        String remote_filename = results[1];
        log.debug("group_name: " + group_name + ", remote_filename: " + remote_filename);
        //lr.message("group_name: " + group_name + ", remote_filename: " + remote_filename);
        log.debug(storageClient.get_file_info(group_name, remote_filename).toString());
        //lr.message(storageClient.get_file_info(group_name, remote_filename).toString());

        ServerInfo[] servers = trackerClient.getFetchStorages(trackerServer, group_name, remote_filename);
        if (servers == null) {
            log.debug("get storage servers fail, error code: " + trackerClient.getErrorCode());
            //lr.message("get storage servers fail, error code: " + trackerClient.getErrorCode());
        } else {
            log.debug("storage servers count: " + servers.length);
            //lr.message("storage servers count: " + servers.length);
            for (int k = 0; k < servers.length; k++) {
                log.debug(k + 1 + ". " + servers[k].getIpAddr() + ":" + servers[k].getPort());
                //lr.message(k + 1 + ". " + servers[k].getIpAddr() + ":" + servers[k].getPort());
            }
            log.debug("");
            //lr.message("");
        }

        return 1;
    }


    /**
     * @desc 文件删除
     * @param clientPath
     * @param group_name
     * @param remoteFileName
     * @throws IOException
     * @throws MyException
     */
    public void deleteFile(String clientPath,String group_name,String remoteFileName) throws IOException, MyException {

        log.debug("配置文件:" + clientPath);
        //lr.message("配置文件:" + clientPath);
        ClientGlobal.init(clientPath);

        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();

        StorageServer storageServer = null;
        StorageClient storageClient = new StorageClient(trackerServer, storageServer);

        //String group_name = "group1";
        //String remote_filename = "M00/00/00/wKgxgk5HbLvfP86RAAAAChd9X1Y736.jpg";
        storageClient.delete_file(group_name, remoteFileName);
        log.debug("删除成功:"+remoteFileName);
        //lr.message("删除成功:"+remoteFileName);
    }


    /**
     * @des 文件获取
     * @param clientPath
     * @param group_name
     * @param remoteFileName
     * @throws IOException
     * @throws MyException
     */
    public void getFile(String clientPath,String group_name,String remoteFileName) throws IOException, MyException {

        log.debug("配置文件:" + clientPath);
        ////lr.message("配置文件:" + clientPath);
        ClientGlobal.init(clientPath);
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        StorageServer storageServer = null;
        StorageClient storageClient = new StorageClient(trackerServer, storageServer);

        //String group_name = "group1";
        //String remote_filename = "M00/00/00/wKgxgk5HcFCwvS9QAAANWIusP08057.jpg";
        FileInfo fi = storageClient.get_file_info(group_name, remoteFileName);
        String sourceIpAddr = fi.getSourceIpAddr();
        long size = fi.getFileSize();
        log.debug("ip:" + sourceIpAddr + ",size:" + size);
        //lr.message("ip:" + sourceIpAddr + ",size:" + size);
    }


    /**
     * @desc 下载文件
     * @param clientPath
     * @param group_name
     * @param remoteFileName
     * @param type
     * @throws IOException
     * @throws MyException
     */
    public void downFile(String clientPath,String group_name,String remoteFileName,String localeFileName,String type) throws IOException, MyException {

        log.debug("配置文件:" + clientPath);
        ////lr.message("配置文件:" + clientPath);
        ClientGlobal.init(clientPath);
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        StorageServer storageServer = null;
        StorageClient storageClient = new StorageClient(trackerServer, storageServer);
        //获取二进制图片文件
        byte[] df =storageClient.download_file(group_name, remoteFileName);

        //FileUtil.saveImage(df, localeFileName, type);

    }

}